<?php

class UploadFilesController extends RController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
    public $defaultAction = 'admin';
	public $layout='//layouts/lay_column2';
    public $menu=array();
    public $moduleName="导入检测数据";	//此处修改本模块名称
    
    public function init()
	{
    	$leftmenu = 'yunying';	//此处修改模块所属菜单
		$this->menu = Yii::app()->params[$leftmenu];
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'rights', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
				'model'=>$this->loadModel($id),
		));
	}
	
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('BtBattery');
		$this->render('index',array(
				'dataProvider'=>$dataProvider,
		));
	}
	
	/**
	 * Lists all models.
	 */

	
	public function actionAdmin()
	{
		$uploadTempPath='C:/';
		$model=new BtRunData;
		$error = "电池数据存储错误,请检查数据的正确性";
		// Uncomment the following line if AJAX validation is needed
		//$this->performAjaxValidation($model);
		//echo 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa';
		/*
		if(isset($_POST['BtRunData']))
		{
		*/

			$file1=CUploadedFile::getInstance($model,'image');
			if($file1)
			{
				$filename=$file1->getName();
				$filename1 = $uploadTempPath.$filename;
				if(file_exists($filename1))
					$filename1 = $uploadTempPath.uniqid("uploadfile");
				$file1->saveAs($filename1);
				//$model->attributes=$_POST['BtRunData'];
				$file = fopen($filename1, "r") or exit("failed to open file\n");
				//battery group 1st line 
				
				$line = fgets($file);
				$data = substr($line,0,10);
				$BTKEY_V1 = $data[9] >='0' && $data[9] <= '9' ? substr($line,0,10):
				 ($data[8] >='0' && $data[8] <= '9' ? substr($line,0,9) : substr($line,0,8));

		//to justify the auth by user 2012.11.25					 
		$bases;
		$sqlbase;
		//get batterys from userid
		$mUser=User::model()->findByPk(Yii::app()->user->id);
		$unit_level = $mUser->unit_level;
		$unit_id = $mUser->unit_id;
		$isSuperUser = 0;
		//get right by uid 
		switch ($mUser->unit_level){
			case 4:
				$sqlbase = "select * from mtsys_base where BASE_ID = ".$unit_id;
				break;
			case 3:
				$sqlbase = "select * from mtsys_base where COUNTY_ID = ".$unit_id; 
				break;
			case 2:
				$sqlbase = "select * from mtsys_base where CITY_ID = ".$unit_id;			 
				break;
			case 1:
				$sqlbase = "select * from mtsys_base where PROVINCE_ID = ".$unit_id;		 
				break;
			case 0:
				$isSuperUser = 1;			 
				break;
			default:
				break;
		}
		$basearray = array();
		$bases = null;
		
		if($mUser->unit_level == 4){//add by zhouyu
			$bases = User::model()->getBases($mUser->id);
		}else{
			if($isSuperUser == 0)
				$bases = new CSqlDataProvider($sqlbase, array());
		}
		
		$transaction = Yii::app()->db->beginTransaction (); //创建事务
		try{
			if($bases != null && $isSuperUser == 0 ){
 			
			if($mUser->unit_level == 4){
				$basesData = $bases;
			}else{
				$basesData = $bases->getData();
			}
				
 			foreach($basesData as $base ){
 				array_push($basearray , $base["BASE_ID"]);
 			}			
 			// to get the batterys' baseid
 			$sqlbaseId = "select base_N from bt_batterys where RECORD_ID = "."'".$BTKEY_V1."'";
 			$baseN = new CSqlDataProvider($sqlbaseId, array());			 
 			$batteryId = $baseN->getData();
 			 
 			
 			$hasBaseId = 0;
 			if($batteryId != null ){
 				foreach($basearray as $baseId ){					 
 					if($baseId == $batteryId[0]["base_N"]){
 						$hasBaseId = 1; 						 
 						break; 											
 					}		
 				}
 			}else{
 				$error = '数据库里面没有对应的电池组！' ;
 				throw   new Exception("");
 			}
 			if($hasBaseId == 0){
 				$error = '你没有权限上传此数据文件,请认真核对数据文件第一行内容与电池组编码保持一致' ;
 				 throw   new Exception("");
 			} 
 		}
			//}}}}}}}}}}}		
			// count the stdconduct
 				$sqlConduct = "select STDINNER_V , YELLOWVALUE_N, REDVALUE_N from bt_batterys as bt , dict_battery as db where
 				bt.BATTERYTYPE_V = db.record_id and bt.RECORD_ID = "."'".$BTKEY_V1."'";
 				$stdData = new CSqlDataProvider($sqlConduct, array());	
 				$stddDdata =  $stdData->getData();
 				if($stddDdata == null){
 					$error = '电池组的电池组编码可能存在问题，请检查导数数据记事本文件的第一行编码' ;
 					throw   new Exception("");
 				}
 				$stdConduct =  $stddDdata[0]["STDINNER_V"];
 				$stdYelValue = $stddDdata[0]["YELLOWVALUE_N"]; //add by zhouyu
 				$stdRedValue = $stddDdata[0]["REDVALUE_N"];
 				
				//compatity and vol 
				$line = fgets($file);
				$compatity = substr($line,0,4);
				$VOL_N1= substr($line,8,10);
				//
				$line = fgets($file);
				$date_time = substr($line,0,10);
				//
				$line = fgets($file);
				$bt_total = substr($line,0,3);
				$conduct = substr($line,5,10);
				//
				$line = fgets($file);
				$d_conduct = substr($line,0,5);
				$w_conduct = substr($line,5,10);
				
				
				//try{
				//to store the data to bt_batterys
				
				$model->BASE_N = $BTKEY_V1;

				//echo $BTKEY_V1."dadfadsf";
				$batterys = BtBatterys::Model()->findByPk($BTKEY_V1);
				////var_dump($batterys);
				if($batterys == null){
					//todo prompt user					
					$error = '数据库里面没有对应的电池组！' ;
					throw   new Exception("");
					
					//die();
				}
					
				$base_id = $batterys["BASE_N"];
				$bts_type_id = $batterys["BASE_TYPE"];
				//var_dump($base_id);
				$base = MtsysBase::Model()->findByPk($base_id);
				$bts_type = MtsysBasetype::Model()->findByPk($bts_type_id);
				if($bts_type == null){
					//todo prompt user
					$error = '数据库里面没有对应的电池组类型' ;
					throw   new Exception("");
					//die();
				}
				$yWarnRedMax = $bts_type["YELTHRMAXRED_N"];//->YELTHRMAXRED_N;
				$yWarnYellowMax = $bts_type["YELTHRMAXYEL_N"];//->YELTHRMAXYEL_N;
				$gWarnRedMax = $bts_type["GRETHRMAXRED_N"];//->GRETHRMAXYEL_N;
				$gWarnYellowMax = $bts_type["GRETHRMAXYEL_N"];//->GRETHRMAXRED_N;
				
				/*
				$base_type = MtsysBasetype::Model()->findByPk($base["BASE_TYPE"]);
				////var_dump($base_type);

				if($base_type == null){
					//todo prompt user
					$error = '数据库里面没有对应的站点类型' ;
					throw   new Exception("");
					//die();
				}
				$yWarnRedMax = $base_type["YELTHRMAXRED_N"];//->YELTHRMAXRED_N;
				$yWarnYellowMax = $base_type["YELTHRMAXYEL_N"];//->YELTHRMAXYEL_N;
				$gWarnRedMax = $base_type["GRETHRMAXRED_N"];//->GRETHRMAXYEL_N;
				$gWarnYellowMax = $base_type["GRETHRMAXYEL_N"];//->GRETHRMAXRED_N;
				*/
				
				$sum_red = 0;
				$sum_green = 0;
				$sum_yellow = 0;
				$i =1;
				$battery;
				$dict_battery = DictBattery::Model()->findByPk($batterys->BATTERYTYPE_V);
				////var_dump($dict_battery);
				if($dict_battery == null){
					//todo prompt user										
					$error = '数据库里面没有对应的电池类型' ;
					throw   new Exception("");
				}
			//	echo "dict_battery->B0".$dict_battery->B0;
			//	echo "dict_battery->B1".$dict_battery->B1;
				if(( $dict_battery->B0 > 1024 || $dict_battery->B0 <(-1024) ) || ($dict_battery->B1 > 1024 || $dict_battery->B1 <(-1024)  )){
					//todo prompt user

					$error = '电池类型的B0 和 B1越界' ;	
					throw   new Exception("");
				}
				
				
				while(!feof($file)){
					$base_id = $batterys->BASE_N;
					$battery = BtBattery::Model()->find("GROUP_V=:GID  and  SERIAL_N=:SID",array(':GID'=>$BTKEY_V1,':SID'=>$i));
					
					if($battery == null){
						//to insert new row
						$battery = new BtBattery ;
						$battery->SERIAL_N= $i;
						$battery->GROUP_V= $BTKEY_V1;
						//echo "battery is null";
						//die();
						
					}					
					$model=new BtRunData;
					$line = fgets($file);
					if(strlen($line) < 8)
						continue;
					$i_voltage = substr($line,0,5);
					$i_conduct = substr($line,5,10);
					
					//todo: insert into db
					//$model->attributes=$_POST['BtRunData'];
					$model->BTKEY_V = $BTKEY_V1;  //电池组
					$model->BASE_N = $base_id;
					$model->VOL_N = (intval($i_voltage))/1000; //add by zhouyu 除以100
					$model->BTSERIALNO_V =  $battery->SERIAL_N;
					//$model->CURINNER_N = intval($i_conduct); 
					
					$battery->BASE_N= $base_id; //站点
					$battery->CURVAL_N= $model->VOL_N ; //电压
					
					//echo "FORCASTVOLUME_N=".$battery->FORCASTVOLUME_N;
					//echo "B1=".$dict_battery->B1 ;
					$battery->CURINNER_N= (intval($i_conduct))/1000; //内阻 //add by zhouyu 除以100
					$model->INTER_N = $battery->CURINNER_N;
					
					$forcastv = floatval($dict_battery->B0) + floatval($dict_battery->B1)  * (intval($i_conduct))/1000; //change by zhouyu
					$battery->FORCASTVOLUME_N= round($forcastv, 4) > 0 ? round($forcastv, 4): 0; //预估容量
					$model->FORCASTVOLUME_N =  $battery->FORCASTVOLUME_N;

					$battery->BATTERYTYPE_V = $dict_battery->RECORD_ID;
					$model->RUNTIME_D = $date_time;
					$battery->CURDATE_D= $model->RUNTIME_D  ; //采集时间
					//echo "stdConduct=".$stdConduct;
					//echo "i_conduct=".$battery->CURINNER_N;
					if($battery->CURINNER_N <= $stdYelValue){
						$model->STATUS_N = 0;
						$sum_green ++;
					}elseif($battery->CURINNER_N <= $stdRedValue){
						$model->STATUS_N = 1;
						$sum_yellow ++;
					}else{
						$model->STATUS_N = 2;
						$sum_red ++;
					}	
					$battery->STATUS_N= $model->STATUS_N  ; //状态
					
					if(! $battery->save()){  
						
						$error = '电池数据存储错误,请检查数据的正确性' ;
						throw   new Exception("");
						
					}
					if(!$model->save()){
						$error = '电池历史数据存储错误,请检查数据的正确性' ;
						throw   new Exception("");
						
						//throw new CHttpException();
					}

					$i ++;			
				}//while	
				//echo 	"green".$sum_green."yellow".$sum_yellow."red".$sum_red;
				//update batterys
				$batterys->CUR_DATE = $date_time;
				$batterys->GREEN = $sum_green;
				$batterys->YELLOW = $sum_yellow;
				$batterys->RED = $sum_red;
				
				//count the status
				if($sum_red >$yWarnRedMax || $sum_yellow >$yWarnYellowMax || ($sum_red + $sum_yellow) >  $yWarnYellowMax){ //add by zhouyu
					$batterys->STATUS_N = 2;
				}else if($sum_yellow > $gWarnYellowMax||$sum_red >$gWarnRedMax || ($sum_red + $sum_yellow) > $gWarnYellowMax){
					$batterys->STATUS_N = 1;
				}else{
					$batterys->STATUS_N = 0;
				}
				//echo "batterys->STATUS_N ".$batterys->STATUS_N ;
				/*
				$batterys->CUR_DATE = $date_time;
				$batterys->CUR_DATE = $date_time;
				$batterys->CUR_DATE = $date_time;
				*/
	
				if($batterys->save()){  
					
					//echo "batterys->save() ok";
					
				}	
				else{
					//var_dump($batterys) ;
					$error = '电池组数据存储错误,请检查数据的正确性' ;
					throw   new Exception("");
				}
				
				$transaction->commit();
				}catch(	Exception $e ){
					//echo "eeeeeeee";
					$transaction->rollback (); //如果操作失败, 数据回滚
					throw new CHttpException(404, $error);
					fclose($file);
					unlink ($filename1);
					/*
					$this->render('admin',array(
							'model'=>$model,
					)); */

					
					//die ( "上传数据存储错误,请检查数据的正确性" );
				}		
			fclose($file);
			//rm file 
			unlink ($filename1);
			$error = '数据导入成功' ;
			throw new CHttpException(200, $error);
			
			}//file exist

			
		
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='bt-rundata-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


